package com.smalls.redshoes.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.smalls.newvideotwo.db.Record;
import com.smalls.newvideotwo.db.VodDao;
import com.smalls.newvideotwo.mvp.bean.MovieDetail;
import com.smalls.newvideotwo.mvp.presenter.GetMovieDetailPresenter;
import com.smalls.newvideotwo.mvp.view.IGetMovieDetailView;
import com.smalls.newvideotwo.util.LogUtil;
import com.smalls.newvideotwo.utils.Constant;
import com.smalls.newvideotwo.utils.Utils;
import com.smalls.redshoes.R;
import com.smalls.redshoes.ui.widget.RSMoreEpisodePopup;
import com.smalls.redshoes.ui.widget.RoundImageView;
import com.smalls.redshoes.ui.widget.ScrollTextView;
import com.smalls.redshoes.util.ActionConfig;
import com.smalls.redshoes.util.SPUtil;

public class VodDetailActivity extends Activity implements View.OnClickListener, IGetMovieDetailView {
    private static String TAG = Constant.baddcoolio2tag?Constant.TAGPREFIXSTR + VodDetailActivity.class.getSimpleName():VodDetailActivity.class.getSimpleName();
    private Button btn_collect;
    private Button btn_play;
    private Button btn_select;
    private boolean hasDeleteCollection = false;
    private ImageLoader imageLoader = ImageLoader.getInstance();
    private RoundImageView iv_picture;
    private LinearLayout ll_actors;
    private LinearLayout ll_country;
    private LinearLayout ll_director;
    private LinearLayout ll_releasedate;
    private LinearLayout ll_type;
    private MovieDetail mProgramModel;
    private VodDao mUserVodCollectionDao;
    private DisplayImageOptions options;
    private ScrollTextView stv_introduction;
    private TextView tv_actors;
    private TextView tv_country;
    private TextView tv_director;
    private TextView tv_name;
    private TextView tv_releasedate;
    private TextView tv_type;
    private RSMoreEpisodePopup mRSMoreEpisodePopup;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vod_detail);
        initView();
        processLogic(savedInstanceState);
    }

    protected void initView() {
        View mContentView = findViewById(R.id.vod_detail_bg);
        btn_play = (Button) findViewById(R.id.btn_play);
        btn_collect = (Button) findViewById(R.id.btn_collect);
        btn_select = (Button) findViewById(R.id.btn_select);
        tv_name = (TextView) findViewById(R.id.tv_name);
        ll_director = (LinearLayout) findViewById(R.id.ll_director);
        tv_director = (TextView) findViewById(R.id.tv_director);
        ll_actors = (LinearLayout) findViewById(R.id.ll_actors);
        tv_actors = (TextView) findViewById(R.id.tv_actors);
        ll_type = (LinearLayout) findViewById(R.id.ll_type);
        tv_type = (TextView) findViewById(R.id.tv_type);
        ll_country = (LinearLayout) findViewById(R.id.ll_country);
        tv_country = (TextView) findViewById(R.id.tv_country);
        ll_releasedate = (LinearLayout) findViewById(R.id.ll_releasedate);
        tv_releasedate = (TextView) findViewById(R.id.tv_releasedate);
        stv_introduction = (ScrollTextView) findViewById(R.id.stv_introduction);
        iv_picture = (RoundImageView) findViewById(R.id.iv_picture);
        mUserVodCollectionDao = new VodDao();
        this.mRSMoreEpisodePopup = new RSMoreEpisodePopup(this, mContentView);
        this.mRSMoreEpisodePopup.setOnEpisodeClickedListener(new RSMoreEpisodePopup.OnEpisodeClickedListener() {
            public void onEpisodeClicked(int position) {
                startPlay(position);
            }
        });
        options = new DisplayImageOptions.Builder().showImageOnLoading(R.drawable.rs_vod_item_bg).showImageForEmptyUri(R.drawable.rs_vod_item_bg).showImageOnFail(R.drawable.rs_vod_item_bg).cacheInMemory(false).cacheOnDisk(true).imageScaleType(ImageScaleType.EXACTLY).bitmapConfig(Bitmap.Config.RGB_565).displayer(new RoundedBitmapDisplayer(5)).build();
        setListener();
    }

    protected void setListener() {
        btn_play.setOnClickListener(this);
        btn_collect.setOnClickListener(this);
        btn_select.setOnClickListener(this);
    }

    protected void processLogic(Bundle savedInstanceState) {
        boolean bGet = getIntent().getBooleanExtra("get",true);
        if(bGet) {
            String movie_id = getIntent().getStringExtra("movie_id");
            String category_id = getIntent().getStringExtra("category_id");
            GetMovieDetailPresenter getMovieDetailPresenter = new GetMovieDetailPresenter(this);
            getMovieDetailPresenter.request(movie_id,category_id,false);
        } else {
            MovieDetail movieDetail = (MovieDetail) getIntent().getSerializableExtra("movie_id");
            updateData(movieDetail);
        }
    }

    public void onResume() {
        super.onResume();
        if(mProgramModel!=null) {
            if (mUserVodCollectionDao.queryRecordByTypeAndId(mProgramModel.getMovie_id()+"_"+Constant.TYPE_FAV, Constant.TYPE_FAV) != null) {
                btn_collect.setText(R.string.remove_from_favorite);
            } else {
                btn_collect.setText(R.string.collect);
            }
            setMovieInfo();
            if (mProgramModel == null
                    || TextUtils.isEmpty(mProgramModel.getMedia_code())
                    || !(ActionConfig.getActionType() == 9
                    || ActionConfig.getActionType() == 8)) {
                setButtons();
            } else {
                updateData(mProgramModel);
            }
        }
    }

    public void onPause() {
        super.onPause();
        btn_play.setVisibility(View.INVISIBLE);
        btn_select.setVisibility(View.INVISIBLE);
    }

    public void onStop() {
        super.onStop();
        ImageLoader.getInstance().clearMemoryCache();
    }

    private String getResouceString(int id) {
        return getResources().getString(id);
    }

    private void setMovieInfo() {
        if (mProgramModel != null) {
            if (TextUtils.isEmpty(mProgramModel.getTitle())) {
                tv_name.setText(getResouceString(R.string.rs_moview_detail_unknow));
            } else {
                tv_name.setText(mProgramModel.getTitle());
            }
            if (TextUtils.isEmpty(mProgramModel.getDirector())) {
                tv_director.setText(getResouceString(R.string.rs_moview_detail_unknow));
            } else {
                tv_director.setText(mProgramModel.getDirector());
            }
            if (TextUtils.isEmpty(mProgramModel.getActors())) {
                tv_actors.setText(getResouceString(R.string.rs_moview_detail_unknow));
            } else {
                tv_actors.setText(mProgramModel.getActors());
            }

            if (!(TextUtils.isEmpty(mProgramModel.getCountry()))) {
                tv_country.setText(mProgramModel.getCountry());
            }

            tv_releasedate.setText(mProgramModel.getRelease_year()+"");

            if (TextUtils.isEmpty(mProgramModel.getDescription())) {
                stv_introduction.setText("");
            } else {
                stv_introduction.setText(mProgramModel.getDescription());
            }
            iv_picture.setImageResource(R.drawable.rs_vod_item_bg);
            setPoster();
            return;
        }
        tv_name.setText(getResouceString(R.string.rs_moview_detail_unknow));
        tv_type.setText("");
        tv_actors.setText(getResouceString(R.string.rs_moview_detail_unknow));
        tv_director.setText(getResouceString(R.string.rs_moview_detail_unknow));
        tv_country.setText(getResouceString(R.string.rs_moview_detail_unknow));
        tv_releasedate.setText(getResouceString(R.string.rs_moview_detail_unknow));
        stv_introduction.setText("");
        btn_collect.setText(R.string.collect);
    }

    private void setPoster() {
        if (mProgramModel.getPhotos() != null) {
            String imgUrl = Utils.getPosterUrl(mProgramModel);
            if (!TextUtils.isEmpty(imgUrl)) {
                imageLoader.displayImage(imgUrl, iv_picture, options);
            }
        }
    }

    private void updateData(MovieDetail programModel) {
        LogUtil.d(TAG, "updateData");
        LogUtil.d(TAG, "collection or history");
        if (programModel != null) {
            mProgramModel = programModel;
            setButtons();
            setMovieInfo();
        }
    }

    private void setButtons() {
        if (mProgramModel == null || mProgramModel.getStreaming() == null || mProgramModel.getStreaming().size() <= 0) {
            btn_play.setVisibility(View.INVISIBLE);
            btn_collect.requestFocus();
        } else {
            if (mProgramModel.getStreaming().size() >= 1
                    && !TextUtils.isEmpty((mProgramModel.getStreaming().get(0)).getMedia_code())) {
                btn_play.setVisibility(View.VISIBLE);
            }
            if (mProgramModel.getStreaming().size() == 1) {
                btn_select.setVisibility(View.INVISIBLE);
            } else {
                btn_select.setVisibility(View.VISIBLE);
                mRSMoreEpisodePopup.setDates(mProgramModel);
            }
        }
        if (btn_play.getVisibility() == View.VISIBLE) {
            btn_play.requestFocus();
        }
    }

    private void startPlay(int select) {
        if (select >= 0 && mProgramModel.getStreaming() != null && mProgramModel.getStreaming().size() > 0 && select < mProgramModel.getStreaming().size()) {
            Intent mStartPlayIntent = new Intent(this, VodPlayActivity.class);
            mStartPlayIntent.putExtra("videoinfo", mProgramModel);
            mStartPlayIntent.putExtra("sets", select);
            startActivity(mStartPlayIntent);
        }
    }

    public void onClick(View v) {
        if (v.getId() == R.id.btn_select) {
            mRSMoreEpisodePopup.changePopupWindowState();
        }
        if (v.getId() == R.id.btn_collect) {
            if (mUserVodCollectionDao.queryRecordByTypeAndId(mProgramModel.getMovie_id()+"_"+Constant.TYPE_FAV, Constant.TYPE_FAV)!=null) {
                mUserVodCollectionDao.deleteByTypeAndId(Constant.TYPE_FAV,mProgramModel.getMovie_id()+"_"+Constant.TYPE_FAV);
            } else {
                Record record = new Record();
                record.setTitle(mProgramModel.getTitle());
                record.setCountry(mProgramModel.getCountry());
                record.setShort_title(mProgramModel.getShort_title());
                record.setMedia_type(mProgramModel.getMedia_type());
                record.setAlbumPic(Utils.getPosterUrl(mProgramModel));
                record.setCategory_id(mProgramModel.getCategory_id());
                record.setTypeId(Constant.TYPE_FAV);
                record.setMovie_id(mProgramModel.getMovie_id()+"_"+Constant.TYPE_FAV);
                record.setAlbumType(mProgramModel.getSubtitle());
                record.setRelease_year(mProgramModel.getRelease_year());
                record.setTime(Utils.getSystemTime());
                Log.i(TAG,"doCollected move_id="+mProgramModel.getMovie_id()+" catory_id="+mProgramModel.getCategory_id());
                mUserVodCollectionDao.addRecords(record);
            }
            btn_collect.setText(mUserVodCollectionDao.queryRecordByTypeAndId(mProgramModel.getMovie_id()+"_"+Constant.TYPE_FAV, Constant.TYPE_FAV)!=null ? R.string.remove_from_favorite : R.string.collect);
        }
        if (v.getId() == R.id.btn_play && mProgramModel.getStreaming() != null && mProgramModel.getStreaming().size() >= 1) {
            if (mProgramModel.getStreaming().size() == 1) {
                startPlay(0);
            } else if (mProgramModel.getStreaming().size() >= 1) {
                startPlay(SPUtil.getInt(this, mProgramModel.getMedia_code(), 0));
            }
        }
    }

    @Override
    public void onSucceedGetMovieDetail(MovieDetail movieDetail) {
        if(movieDetail!=null) {
            mProgramModel = movieDetail;
            updateData(movieDetail);
        }
    }

    @Override
    public void showErrDialogGetMovieDetail(String str) {

    }
}
